package com.example.aop;

import com.alibaba.fastjson.JSONObject;
import com.example.mapper.OperateLogMapper;
import com.example.pojo.OperateLog;
import com.example.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.example.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //操作人ID    因为jwt令牌有登录人信息，所以解析jwt令牌就可以
//        String token = request.getHeader("token");
//        Claims claims = JwtUtils.parseJWT(token);
//        Integer user = (Integer) claims.get("id");
        //  使用链式编程   ↓↓↓
        Integer user = (Integer) JwtUtils.parseJWT(request.getHeader("token")).get("id");
        //操作时间
        LocalDateTime optionTime = LocalDateTime.now();
        //操作类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作方法名
        String methodName = joinPoint.getSignature().getName();
        //操作方法参数
        String args = Arrays.toString(joinPoint.getArgs());
        long start = System.currentTimeMillis(); // 记录方法开始运行时间
        // 调用原始方法
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis(); // 记录方法结束运行时间
        //操作方法返回值
        String returnValue = JSONObject.toJSONString(result);
        //操作耗时
        long costTime = end - start;
        // 记录操作日志
        OperateLog operateLog = new OperateLog(null, user, optionTime, className, methodName, args, returnValue, costTime);
        operateLogMapper.insert(operateLog);
        log.info("AOP记录操作日志：{}", operateLog);
        return result;
    }
}
